/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller;

import CRUD.MemberHome;

import Utility.PostOperationsUtility;

import CRUD.ThreadHome;

import Utility.ThreadOperationsUtility;
import Utility.ThreadPollsUtility;
import Utility.Utility;
import beans.ThreadActionForm;
import beans.VoteAnswer;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import xmlMapping.Ban;
import xmlMapping.Forum;
import xmlMapping.Member;
import xmlMapping.Post;
import xmlMapping.Suspend;
import xmlMapping.Thread;
import xmlMapping.Threadpollschoices;
import xmlMapping.Threadpollsquestions;

/**
 *
 * @author sh
 */
public class ThreadAction extends org.apache.struts.action.Action {
    
    /* forward name="success" path="" */
    
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        Utility utility=new Utility();
        String str;

        int pagenumber=1;//Integer.parseInt(request.getParameter("pagenumber"));
        if(request.getParameter("pagenumber")!=null){
            pagenumber=Integer.parseInt(request.getParameter("pagenumber"));
        }

        MemberHome mHome=new  MemberHome();

        if(request.getParameter("threadid")!=null){
            str=request.getParameter("threadid");
        }else{
            str=(String)request.getAttribute("threadid");
        }
        int tId=Integer.parseInt(str);
        Thread thread=ThreadOperationsUtility.getThread(tId);//new Thread();
        //Set setp=thread.getPosts();
        List post=utility.getPostspage(tId,pagenumber);
     Iterator it= post.iterator();  //setp.iterator();
     while(it.hasNext())
     {
         Post p=(Post)it.next();
         System.out.println("this post id is   "+p.getPostId()+"title "+p.getTitle()+"body"+p.getBody());
     }
        if(it!=null){

        thread.setPosts(new HashSet(post));
        Iterator posts=post.iterator();
         
        while(posts.hasNext()){
            System.out.println(" in posts iterator ");
            Member mem=(Member)((Post)posts.next()).getMember();
           Ban ban=utility.checkBan(mem.getMemberId());
           Suspend sus=utility.checkSuspend(mem.getMemberId());
           if(sus!=null){
               Set setsus=new HashSet();
               setsus.add(sus);
               mem.setSuspendsForMemberId(setsus);
           }else{
               mem.setSuspendsForMemberId(null);
           }


            //System.out.println("xxxxxxxxxxxx"+ban.getReason());
            mem.setBanByMemberId(ban);
        }
        }
        //Set setPost=new HashSet(utility.getPosts(tId));
        //thread.setPosts(setPost);

        Forum forum=thread.getForum();
        thread.setForum(forum);


        /********* Start Part by Abdelmohsen for handling Thread polls ***********/
        ThreadPollsUtility pollsUtility=new ThreadPollsUtility();
        Threadpollsquestions q=pollsUtility.getThreadPollsQuestions(tId);
        if(q!=null){
            ThreadActionForm bean=(ThreadActionForm)form;
            request.setAttribute("question", q.getQuestion());
            Iterator<Threadpollschoices> answersI=q.getThreadpollschoiceses().iterator();
            Vector<VoteAnswer> choices=new Vector<VoteAnswer>();
            VoteAnswer c=null;
            Threadpollschoices choice=null;
            float totalParticipants=0;
            float percent=0;
            while(answersI.hasNext()){
                choice=answersI.next();
                totalParticipants+=choice.getNoofselectors();
            }
            answersI=q.getThreadpollschoiceses().iterator();
            while(answersI.hasNext()){
                choice=answersI.next();
                if(totalParticipants!=0) percent=(choice.getNoofselectors()*100)/totalParticipants;
                c=new VoteAnswer();
                c.setChoice(choice.getChoice());
                c.setPercent(percent);
                c.setId(choice.getChoiceId());
                choices.add(c);
            }
            request.setAttribute("answers", choices);
            if(request.getSession().getAttribute("id")==null) request.setAttribute("vote", "true");
            else{
                
                Member m=mHome.findById((Integer)request.getSession().getAttribute("id"));
                Iterator<Member> voters=q.getMembers().iterator();
                request.setAttribute("vote", "false");
                while(voters.hasNext()){
                    if((int)voters.next().getMemberId()==m.getMemberId()){
                        request.setAttribute("vote", "true");
                    }
                }
            }
        }
        /********* End Part by Abdelmohsen for handling Thread polls ***********/
        /****************pages*********************************/
        int numpost=PostOperationsUtility.getCountPosts(tId);//utility.getCountPosts(tId);
          int numpage;
        int mod=numpost % 10;
        numpage=(numpost-mod)/10;
        if(mod>0 ){

             numpage++;
        }
        request.setAttribute("pagenumber", pagenumber);
        request.setAttribute("numpage", numpage);
        request.setAttribute("thread", thread);
        // labib this part for getting posts that user rank it
        if(request.getSession().getAttribute("id")!=null)
        
        {
        
            System.out.println("id of user is "+(Integer)(request.getSession().getAttribute("id")));
    Member memberposts= mHome.findById((Integer)(request.getSession().getAttribute("id")));
    Set rankedposts=memberposts.getPosts();
    Iterator iter=rankedposts.iterator();
    
     Set<Integer> poid=new TreeSet<Integer>();
        while (iter.hasNext()) {
            Post  object = (Post)iter.next();
            System.out.println(" obj ============="+object.getPostId());
    poid.add(object.getPostId());                    
            
        }
        request.setAttribute("postss", poid);
        }
    
        
        
        return mapping.findForward("postpage");
    }
}
